//curl --unix-socket /var/run/docker.sock http:/v1.41/containers/json 
const Docker = require('dockerode');

const ppy_docker = (ctx) => {
    console.log('有新的客户端连接了')
  
    let container_id = ctx.query.container_id;
    console.log(`container_id:${container_id}`);
    
    const docker = new Docker({socketPath: '/var/run/docker.sock'});
    const container = docker.getContainer(container_id);
    
    const options = {
        "Cmd": ["/bin/bash"],
        "AttachStdin": true,
        "AttachStdout": true,
        "Tty": true
        };

    let tty_stream = null;
    container.exec(options, function(err, exec) {
        if (err) return;
        exec.start({hijack: true, stdin: true}, function(err, stream) {
            if (err) return;
            tty_stream = stream;
            ctx.websocket.on('message', (data) => {
                tty_stream.write(data);
            });
            tty_stream.on("data", function(data) {
                //console.log("msg", data);
                ctx.websocket.send(data);
            });
        });
    });
    
    ctx.websocket.on('close', () => {
        if(tty_stream != null){
            tty_stream.end(); 
        }
        console.log('docker_ws :: close');
    });
}

module.exports = {
    ppy_docker
}

